package com.heima.search.service.impl;

import com.heima.es.service.EsService;
import com.heima.model.common.constants.search.SearchConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.exception.CustException;
import com.heima.model.search.dtos.UserSearchDTO;
import com.heima.model.search.vo.SearchArticleVO;
import com.heima.model.threadLocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {
    @Autowired
    private EsService<SearchArticleVO> esService;

    @Value("${file.minio.readPath}")
    private String readPath;

    @Value("${file.oss.web-site}")
    private String webSite;

    @Autowired
    private ApUserSearchService apUserSearchService;

    @Override
    public ResponseResult search(UserSearchDTO dto) {
        // 1 校验参数
        String searchWords = dto.getSearchWords();
        if (StringUtils.isBlank(searchWords)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "搜索条件内容不能为空");
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        ApUser user = AppThreadLocalUtils.getUser();
        if (user != null) {
            dto.setLoginUserId(user.getId());
        }
        // 异步调用保存用户输入关键词记录
        apUserSearchService.insert(dto);
        // 2 构建搜索请求对象 builder.query
        SearchSourceBuilder builder = new SearchSourceBuilder();
        // 2.1.1 创建布尔条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 2.1.2 创建分词查询条件  match查询title
        MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("title", dto.getSearchWords());
        boolQuery.must(matchQuery);
        // 2.1.3  创建范围查询条件 range查询publishTime
        boolQuery.must(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime()));
        builder.query(boolQuery);
        // 2.2 构建高亮条件  builder.highlight
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        // 2.2.1 将title设置为高亮
        highlightBuilder.field("title");
        // 2.2.2 设置前置和后置标签
        highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
        highlightBuilder.postTags("</font>");
        builder.highlighter(highlightBuilder);
        // 2.3 构建排序条件  builder.sort 发布时间降序(默认按照score)
        builder.sort("publishTime", SortOrder.DESC);
        // 2.4 构建分页条件  builder.from(0) builder.size(pageSize)
        builder.size(dto.getPageSize());
        // 3 执行搜索 并封装返回结果
        PageResponseResult searchResult = esService.search(builder, SearchArticleVO.class, SearchConstants.ARTICLE_INDEX_NAME);
        List<SearchArticleVO> searchResultList = (List<SearchArticleVO>) searchResult.getData();
        for (SearchArticleVO searchArticleVO : searchResultList) {
            // 3.1 staticUrl 加上访问前缀
            searchArticleVO.setStaticUrl(readPath + searchArticleVO.getStaticUrl());
            // 3.2 image 封面图片加上访问前缀
            String images = searchArticleVO.getImages();
            if (StringUtils.isNotBlank(images)) {
                String[] split = images.split(",");
                images = Arrays.stream(split).map(url -> webSite + url
                ).collect(Collectors.joining(","));
                searchArticleVO.setImages(images);
            }
        }
        return searchResult;
    }

    @Override
    public void saveArticle(SearchArticleVO article) {
        esService.save(article, SearchConstants.ARTICLE_INDEX_NAME);
    }

    @Override
    public void deleteArticle(String articleId) {
        esService.deleteById(articleId, SearchConstants.ARTICLE_INDEX_NAME);
    }
}
